package com.dabai.linktools;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.dabai.linktools.databinding.ActivityDownloadBinding;
import com.dabai.linktools.utils.DabaiUtils;
import com.dabai.linktools.utils.FileLengthUtils;
import com.download.library.DownloadImpl;
import com.download.library.DownloadListenerAdapter;
import com.download.library.Extra;

import java.io.File;

public class DownloadActivity extends AppCompatActivity {


    private static final String TAG = "dabaizzz";
    ActivityDownloadBinding adb;

    //下载名称和文件
    String downlink, downfilepath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        adb = ActivityDownloadBinding.inflate(LayoutInflater.from(this));
        setContentView(adb.getRoot());


        Intent intent = getIntent();
        downlink = intent.getStringExtra("downlink");
        downfilepath = intent.getStringExtra("downfile");

        adb.textView.setText("下载链接 : " + downlink);
        adb.textView2.setText("下载到 : " + downfilepath);

        downloadService(downlink, downfilepath);

    }

    private void downloadService(String downlink, String downfilepath) {

        Log.d(TAG, "地址: " + downlink);
        Log.d(TAG, "目录: " + downfilepath);

        new Thread(() -> {

            File downfile = new File(downfilepath);

            if (downfile.exists()) {
                runOnUiThread(() -> {
                    Toast.makeText(this, "已经存在!", Toast.LENGTH_SHORT).show();
                    vibrator();
                    adb.sharebtn.setVisibility(View.VISIBLE);
                });
                return;
            }

            DownloadImpl.getInstance()
                    .with(getApplicationContext())
                    .addHeader("Accept", "*/*")
                    .addHeader("User-Agent", "dabai2017")
                    .target(downfile)
                    .url(downlink)
                    .enqueue(new DownloadListenerAdapter() {
                        @Override
                        public void onStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength, Extra extra) {
                            super.onStart(url, userAgent, contentDisposition, mimetype, contentLength, extra);

                        }

                        @Override
                        public void onProgress(String url, long downloaded, long length, long usedTime) {
                            super.onProgress(url, downloaded, length, usedTime);
                            runOnUiThread(() -> {
                                adb.textView3.setText("进度:" + FileLengthUtils.FormetFileSize(downloaded) + "/" + FileLengthUtils.FormetFileSize(length));
                                adb.progressBar.setProgress((int) (downloaded * 100 / length));
                            });
                        }

                        @Override
                        public boolean onResult(Throwable throwable, Uri path, String url, Extra extra) {

                            runOnUiThread(() -> {
                                Toast.makeText(DownloadActivity.this, "下载完成!", Toast.LENGTH_SHORT).show();
                                adb.sharebtn.setVisibility(View.VISIBLE);
                            });

                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, path));
                            vibrator();

                            return super.onResult(throwable, path, url, extra);
                        }
                    });


        }).start();


    }


    /**
     * 震动 1下
     */
    public void vibrator() {
        Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(100);
    }

    /**
     * 回到桌面
     */
    private void gohome() {
        Intent intent2 = new Intent();
        // 为Intent设置Action、Category属性
        intent2.setAction(Intent.ACTION_MAIN);// "android.intent.action.MAIN"
        intent2.addCategory(Intent.CATEGORY_HOME); //"android.intent.category.HOME"
        startActivity(intent2);
    }

    //菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.gohome, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.gohome:
                gohome();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    public void share_file(View view) {
        new DabaiUtils().shareFile(this, downfilepath);
    }

    //声明一个long类型变量：用于存放上一点击“返回键”的时刻
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次退出程序!", Toast.LENGTH_SHORT).show();
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
